<template>
  <div>
    <table-search
      ref="tableSearch"
      title="线下采购订单"
      selection
      :columns="columns"
      :api="getList"
      :tabs-options="tabsOptions"
      @selection-change="onSelectionChange"
    >
      <div
        slot="table-title"
        style="flex: 1; display: flex; justify-content: flex-end"
      >
        <el-button
          type="primary"
          size="mini"
          @click="onExportExcel"
          :disabled="!selection.length"
          >导出所选订单</el-button
        >
        <el-upload
          class="upload-box"
          :action="uploadExcel.url"
          :name="uploadExcel.name"
          accept=".xls, .xlsx"
          :on-success="uploadSuccess"
          :show-file-list="false"
          style="margin-left: 10px"
        >
          <el-button
            class="filing-button"
            type="primary"
            size="mini"
            slot="trigger"
            >采购单导入</el-button
          >
        </el-upload>
        <el-button
          type="primary"
          size="mini"
          @click="onExport"
          style="margin-left: 10px"
          >模板下载</el-button
        >
      </div>

      <template #orderTime="{ row }">
        {{ row.orderTime }}
      </template>
      <template #purchasePrice="{ row }"> {{ row.purchasePrice }}元 </template>
      <template #salePrice="{ row }"> {{ row.salePrice }}元 </template>

      <template #orderState="{ row }">
        <div class="hasEdit" v-if="row.updateState == 1">
          <span class="text">改</span>
        </div>
        <p>
          {{ code2name(row.orderState, orderStatusList) }}
        </p>
      </template>

      <template #payBackState="{ row }">
        <p>
          {{ row.payBackState == 1 ? '已回款' : '未回款' }}
        </p>
      </template>

      <template #operate="{ row }">
        <router-link
          :to="`/customer/PO/detail?id=${row.purchaseOrderId}`"
          target="_blank"
          style="margin: 0 5px"
        >
          <el-button type="text" size="small">查看详情</el-button>
        </router-link>

        <el-popconfirm
          v-if="row.orderState == 1"
          title="该采购单确认发货？"
          @onConfirm="confirmShip(row)"
          style="margin: 0 5px"
        >
          <el-button slot="reference" type="text" size="small">
            确认发货
          </el-button>
        </el-popconfirm>
        <el-popconfirm
          v-if="row.orderState == 2"
          title="该采购单确认收货？"
          @onConfirm="onReceipt(row)"
          style="margin: 0 5px"
        >
          <el-button slot="reference" type="text" size="small">
            确认收货
          </el-button>
        </el-popconfirm>
        <el-popconfirm
          v-if="row.payBackState == 0"
          title="该采购单确认回款？"
          @onConfirm="onPayBack(row)"
          style="margin: 0 5px"
        >
          <el-button slot="reference" type="text" size="small">
            确认回款
          </el-button>
        </el-popconfirm>
        <el-popconfirm
          v-if="row.orderState == 3"
          title="该采购单确认完成？"
          @onConfirm="onConfirmOrder(row)"
          style="margin: 0 5px"
        >
          <el-button slot="reference" type="text" size="small">
            确认完成
          </el-button>
        </el-popconfirm>

        <el-popconfirm
          v-if="row.orderState == 1 || row.orderState == 2"
          title="确认要取消该采购单吗？"
          @onConfirm="onCancel(row)"
          style="margin: 0 5px"
        >
          <el-button slot="reference" type="text" size="small">
            取消订单
          </el-button>
        </el-popconfirm>
      </template>
    </table-search>
    <el-dialog
      :title="'确认' + (POState.isReceipt ? '收' : '发') + '货'"
      :visible.sync="POState.show"
      width="60%"
    >
      <el-table
        :data="POState.data"
        border
        :header-cell-style="{
          backgroundColor: '#f5f5f5',
          color: '#333',
          fontWeight: 'bold',
          textAlign: 'center',
        }"
        max-height="500"
        @selection-change="handleSelectionChange"
        row-class-name="batchShipBasicRow"
        :cell-class-name="batchShipBasicCellMethod"
        :span-method="batchShipBasicMethod"
      >
        <el-table-column type="selection" align="center" width="55">
        </el-table-column>
        <el-table-column label="商品名称" align="center">
          <template slot-scope="scope">
            <el-table
              class="batchShipTable"
              :data="scope.row.goodList"
              :show-header="false"
              :span-method="
                batchShipMethod.bind(null, scope.row.goodList.length)
              "
            >
              <el-table-column align="center" prop="goodName">
              </el-table-column>
              <el-table-column width="250" align="center" prop="goodModel">
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="规格型号" align="center" width="250">
          <template slot-scope="scope" v-if="!POState.isReceipt">
            <el-input
              :value="scope.row.logisticsNo"
              @input="$set(scope.row, 'logisticsNo', $event)"
              placeholder="填写物流单号"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="物流单号" width="250" v-if="!POState.isReceipt">
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="POState.show = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="savePOState">确 定 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  defineComponent,
  computed,
  reactive,
  getCurrentInstance,
  ref,
} from '@vue/composition-api'
import TableSearch from '@/components/TableSearch/TableSearch'
import { createTableColumns } from '@/components/TableSearch/utils'
import dict from '@/lib/dict'

import {
  page,
  cancelOrder,
  batchConfirmShip,
  batchConfirmReceipt,
  confirmOrder,
  confirmPayBack,
  downloadExcel,
  orderCount,
  confirmShipGoodInfo,
  confirmReceiptGoodInfo,
} from '@/api/PO'

import { downLoadFile } from '@/lib/utils'
import Http from '@/lib/http'

const { orderStatusList } = dict

export default defineComponent({
  components: {
    TableSearch,
  },
  setup() {
    const instance = getCurrentInstance()
    console.log(instance)

    const columns = computed(() => {
      return createTableColumns([
        ['订单编号', 'orderId', { search: true }],
        ['业务类型', 'businessType', { search: true }],
        [
          '下单时间',
          'orderTime',
          { search: { key: ['startTime', 'endTime'] }, width: 160 },
        ],
        ['采购金额(元)', 'purchasePrice'],
        ['订单金额(元)', 'salePrice'],
        ['客户名称', 'clientUnitName', { search: true }],
        ['收货地址', 'address'],
        ['订单状态', 'orderState'],
        ['回款状态', 'payBackState'],
        ['业务员', 'clientName', { search: true }],
        ['操作', 'operate'],
      ])
    })

    const tabsOptions = reactive({
      list: [{ code: '', desc: '全部采购单' }, ...orderStatusList],
      data: {},
      searchKey: 'orderState',
    })
    const uploadExcel = reactive({
      url: '/api/offline/importOfflineOrder',
      name: 'excel',
    })

    const uploadSuccess = (res, file, fileList) => {
      if (res.success) {
        instance.$message({
          type: 'success',
          message: res.desc,
        })
        instance.$refs.tableSearch.reload()
      } else instance.$message.error(res.desc)
    }

    const code2name = (code, list) => {
      for (const item of list) {
        if (item.code == code) {
          return item.desc
        }
      }
    }

    const getList = async (pageIndex, pageSize, query) => {
      getOrderCount()
      const result = await page(pageIndex, pageSize, query)
      return result
    }

    const getOrderCount = async () => {
      const result = await orderCount()
      getDataCount(result)
    }

    const getDataCount = async result => {
      const dataKeyMap = {
        1: 'waitShipCount',
        2: 'waitReceiptCount',
        3: 'confirmReceiptCount',
        99: 'finishCount',
        0: 'cancelCount',
        '': 'totalCount',
      }
      const data = {}
      tabsOptions.list.forEach(item => {
        data[item.code] = result[dataKeyMap[item.code]]
      })
      tabsOptions.data = data
    }

    const onCancel = async item => {
      const loading = instance.$loading()
      try {
        await cancelOrder(item.purchaseOrderId)
        instance.$message({
          type: 'success',
          message: '取消报备成功',
        })
        instance.$refs.tableSearch.reload()
      } catch (error) {
        console.error(error)
      }
      loading.close()
    }

    const POState = reactive({
      isReceipt: false,
      show: false,
      loading: false,
      id: null,
      data: [],
    })
    const confirmShip = async item => {
      const loading = instance.$loading()
      POState.isReceipt = false
      POState.show = true

      const result = await confirmShipGoodInfo(item.purchaseOrderId)
      POState.data = result
      loading.close()
    }

    const onReceipt = async item => {
      const loading = instance.$loading()
      POState.isReceipt = true
      POState.show = true

      const result = await confirmReceiptGoodInfo(item.purchaseOrderId)
      POState.data = result
      loading.close()
    }

    const onConfirmOrder = async item => {
      const loading = instance.$loading()

      try {
        await confirmOrder(item.purchaseOrderId)
        instance.$message.success('操作成功')
        instance.$refs.tableSearch.reload()
      } catch (error) {
        console.error(error)
      }
      loading.close()
    }

    const onPayBack = async item => {
      const loading = instance.$loading()

      try {
        await confirmPayBack(item.purchaseOrderId)
        instance.$message.success('操作成功')
        instance.$refs.tableSearch.reload()
      } catch (error) {
        console.error(error)
      }
      loading.close()
    }

    const selection = ref([])
    const onSelectionChange = val => {
      selection.value = val
    }

    const onExport = async () => {
      const loading = instance.$loading()
      try {
        downLoadFile(await downloadExcel())
      } catch (error) {
        console.error(error)
      }
      loading.close()
    }

    const onExportExcel = () => {
      downLoadFile(
        Http.getUrl(
          `/offline/exportOrderExcel?purchaseOrderIds=${selection.value.map(
            item => item.purchaseOrderId
          )}`
        )
      )
    }
    const multipleSelection = ref([])
    const handleSelectionChange = val => {
      multipleSelection.value = val
    }
    const savePOState = async () => {
      let arr = []
      if (!POState.isReceipt) {
        multipleSelection.value.some(item => {
          arr.push({
            purchaseOrderId: item.purchaseOrderId,
            parentPurchaseOrderId: item.parentPurchaseOrderId,
            logisticsNo: item.logisticsNo,
          })
        })
        if (arr.length < 1) {
          instance.$message.error('请勾选要发货的商品')
          return
        }
        const loading = instance.$loading()
        try {
          await batchConfirmShip(arr)
          instance.$message.success('操作成功')
          POState.show = false
          instance.$refs.tableSearch.reload()
        } catch (error) {
          console.error(error)
        }
        loading.close()
      } else {
        multipleSelection.value.map(item => {
          arr.push({
            purchaseOrderId: item.purchaseOrderId,
            parentPurchaseOrderId: item.parentPurchaseOrderId,
          })
        })
        if (arr.length < 1) {
          instance.$message.error('请勾选要收货的商品')
          return
        }
        const loading = instance.$loading()
        try {
          await batchConfirmReceipt(arr)
          instance.$message.success('操作成功')
          POState.show = false
          instance.$refs.tableSearch.reload()
        } catch (error) {
          console.error(error)
        }
        loading.close()
      }
    }
    const batchShipBasicMethod = ({ row, column, rowIndex, columnIndex }) => {
      if (columnIndex == 1) return [1, 2]
    }
    const batchShipMethod = (
      length,
      { row, column, rowIndex, columnIndex }
    ) => {
      if (length > 1 && columnIndex > 1) {
        return [length, 1]
      }
    }
    const batchShipBasicCellMethod = ({
      row,
      column,
      rowIndex,
      columnIndex,
    }) => {
      if (columnIndex == 1) {
        return 'batchShipBasicCell'
      }
    }
    return {
      columns,
      getList,
      tabsOptions,
      onCancel,
      confirmShip,
      onReceipt,
      orderStatusList,
      code2name,
      onSelectionChange,
      onExport,
      selection,
      POState,
      multipleSelection,
      handleSelectionChange,
      savePOState,
      onConfirmOrder,
      onPayBack,
      uploadExcel,
      uploadSuccess,
      onExportExcel,
      batchShipMethod,
      batchShipBasicMethod,
      batchShipBasicCellMethod,
    }
  },
})
</script>

<style lang="scss" scoped>
.hasEdit {
  position: absolute;
  top: 0;
  left: 0;
  &::before {
    content: '';
    display: block;
    width: 0;
    height: 0;
    border-top: 30px solid red;
    border-right: 30px solid transparent;
  }
  .text {
    position: absolute;
    top: -3px;
    left: 2px;
    color: #fff;
    font-size: 12px;
  }
}
</style>
<style lang="less" >
.batchShipBasicRow > td {
  padding: 0;
}
.el-table.batchShipTable::before {
  height: 0;
}
.batchShipBasicCell .cell {
  padding: 0;
}
</style>
